<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    title="导入业务表"
    width="70%"
    @ok="handleSubmit"
  >
    <BasicTable @register="registerTable" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ImportDrawer">
  import {
    BasicTable,
    useTable,
  } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { selectTableColumns, selectTableSearchFormSchema } from './index-option';
  import { getSelectTablePage, importTable } from '/@/api/sys/gen';
  import { useMessage } from '/@/hooks/web/useMessage';

  const emit = defineEmits(['success']);
  const { createMessage } = useMessage();

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async () => {
    reload();
    setSelectedRowKeys([]);
  });

  const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys }] = useTable({
    api: getSelectTablePage,
    rowKey: 'tableName',
    columns: selectTableColumns,
    formConfig: {
      labelWidth: 80,
      schemas: selectTableSearchFormSchema,
    },
    rowSelection: { type: 'checkbox' },
    useSearchForm: true,
    bordered: true,
    canResize: false,
    ellipsis: true,
  });

  async function handleSubmit() {
    try {
      const selectedKeys = getSelectRowKeys();
      if (selectedKeys.length < 1) {
        createMessage.error('请至少选择1张表');
        return false;
      }
      if (selectedKeys.length > 10) {
        createMessage.error('最多选择10张表');
        return false;
      }
      const param = { tableNames: selectedKeys };
      const res = await importTable(param);
      createMessage.success(res.msg);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
